﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml;

namespace QuailDashboard.View.Web.RegExUrlMapping
{
    public class RegExUrlMappingConfigHandler : IConfigurationSectionHandler
    {
        private XmlNode _section;

        /// <summary>
        /// Creates a configuration section handler.
        /// </summary>
        /// <returns>
        /// The created section handler object.
        /// </returns>
        /// <param name="parent">Parent object.</param>
        /// <param name="configContext">Configuration context object.</param>
        /// <param name="section">Section XML node.</param><filterpriority>2</filterpriority>
        public object Create(object parent, object configContext, XmlNode section)
        {
            _section = section;
            return this;
        }

        internal bool Enabled
        {
            get
            {
                return _section.Attributes["enabled"].Value.ToLower() == "true";
            }
        }

        internal string MappedUrl(string url)
        {
            foreach (XmlNode x in _section.ChildNodes)
            {
                var reg = new Regex(x.Attributes["url"].Value, RegexOptions.IgnoreCase);

                if (reg.Match(url).Success)
                    return reg.Replace(url, x.Attributes["mappedUrl"].Value);
            }

            return string.Empty;
        }
    }
}
